﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Abc.Utils.Module.Elasticsearch;
using Elasticsearch.Net;
using Furion.Logging;
using Microsoft.Extensions.DependencyInjection;
using Nest;
using NPOI.SS.Formula.Functions;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Abc.Utils;
public static class EsLoggingExtension
{
    /// <summary>
    /// 添加ES服务
    /// </summary>
    /// <param name="services"></param>
    public static void AddEsLog(this IServiceCollection services)
    {
        services.AddConfigurableOptions<EsLoggingConfigOptions>();
        services.AddDatabaseLogging<ESLoggingWriter>(options =>
        {

        });
        services.AddSingleton<IEsLoggingProvider, EsLoggingProvider>();


        //此处进行索引创建。防止多次调用索引创建导致问题
        CreateIndex();
    }
    /// <summary>
    /// 创建索引
    /// </summary>
    private static void CreateIndex()
    {
        var _esLogConfigOptions = AppEx.GetConfig<EsLoggingConfigOptions>(isNewObj: true);

        var _client = GetClient();
        var indexName = _esLogConfigOptions.DefaultIndex?.ToLower();
        if (string.IsNullOrWhiteSpace(indexName))
        {
            indexName = "abclogs";
        }
      
      
        //查询es的索引是否存在
        var res = _client.Indices.Exists(_esLogConfigOptions.DefaultIndex);
        //如果es的索引不存在
        if (!res.Exists)
        {
            //不存在，创建索引
            _client.CreateIndex<EsFurionLoggingModel>(indexName);
        }
    }

    private static ElasticClient GetClient()
    {
        var _esLogConfigOptions = AppEx.GetConfig<EsLoggingConfigOptions>();
        var urls = new StaticConnectionPool(_esLogConfigOptions.Urls?.Select(o => new Uri(o)) ?? new List<Uri>());
        var setting = new ConnectionSettings(urls);
        setting = setting.DefaultIndex(_esLogConfigOptions.DefaultIndex);
        //安全验证
        if (!string.IsNullOrWhiteSpace(_esLogConfigOptions.AuthUserName) && !string.IsNullOrWhiteSpace(_esLogConfigOptions.AuthPassword))
        {
            setting = setting.BasicAuthentication(_esLogConfigOptions.AuthUserName, _esLogConfigOptions.AuthPassword);
        }
        var _client = new ElasticClient(setting);

        return _client;
    }

  
}
